/* axios二次封装 */
import Vue from 'vue';
import axios from 'axios';
import env from './env';

// 创建axios实例，默认配置
const axiosObject = axios.create({
  baseURL: env.apiHost,
  timeout: 20000,
  headers: { 'Content-Type': 'application/json;charset=UTF-8' }
});

// 存储username、token
// const funSetToken = (response = {}) => {
//   const { config, headers } = response;
//   // console.log(response,'--------------------------------response----------------------response-------------------------------------------');
//   console.log('config--------------------------------------------------',config)
//   let data={}
//   let phone=''
//   if(config.data){
//     data=JSON.parse(config.data)
//     phone=data.phone
//     // console.log('dataaaaaaaaaaaaaaaaa-',data)
//     // console.log('phone-',phone)
//   }
//   // console.log('phone--------------',phone)
//   window.localStorage.setItem(
//     'tokenData',
//     JSON.stringify({
//       //username: String(config.params?config.params.phone:phone),
//       //token: String(headers.token)
//       token:'4dd308fc-69e7-4a69-a885-fa7c9bddb955'
//     })
//   );
// };

// 封装报错提示，其中204、444是自定义的
// 204：代表接口成功但是后台code!==0；444：代表所有以下情况之外的错误
const showErrMsg = (errCode = 444, customError, resMessage = '数据出错了！') => {
  if (!customError) return;
  const objMsg = {
    204: resMessage,
    400: '请求参数出错！',
    401: '您还没有登录或登录信息已过期！',
    403: '资源禁止访问！',
    404: '未找到接口！',
    405: '接口请求方法错误！',
    444: '网络请求超时，请重试！',
    500: '服务器请求出错！',
    502: '服务器请求出错！'
  };
  if (typeof customError === 'boolean') customError = objMsg[errCode] || '网络请求超时！';
  Vue.prototype.$toast({ message: customError, duration: 3000 });
};

class AxiosRequest {
  constructor() {
    // params={接口参数}、custom={自定义参数}、headers={请求头参数}
    // 自定义参数属性：custom={showLoading:Boolean是否显示loading, noAuth:Boolean是否不需要token验证，true就是不需要, showError:Boolean|String是否显示自定义错误信息}
    this.request = async (method = 'GET', url = '', params = {}, custom = {}, headers = {}) => {
      // 处理loading判断
      let objLoading = null;
      const { showLoading, noAuth } = custom;
      if (showLoading) {
        const loadingText = typeof showLoading === 'boolean' ? '加载中...' : showLoading;
        objLoading = Vue.prototype.MethodShowToast(loadingText, 20000, 'loading');
      }
      headers={'X-Requested-With':'XMLHttpRequest'}
      // 处理请求头
      if (!noAuth) {//需要token授权
        //Object.assign(headers, Vue.prototype.MethodTokenData() || {});
        //let token='2f63b7e2-fae3-4ce5-916b-f8855c2927b6'
        //let obj={token:token}
        let obj={token:localStorage.getItem('token')}
        Object.assign(headers, obj || {});
      }
      // console.log('headers',headers)
      // console.log('custom',custom)
      const axiosParams = { method, url, headers };
      // GET、POST等传参方式不一样
      if (method === 'GET' || method === 'DELETE') {
        axiosParams.params = params;
      } else {
        axiosParams.data = params;
      }
      // console.log('axiosParams',axiosParams)
      // 然后开始请求接口
      return new Promise((resolve, reject) => {
        axiosObject
          .request(axiosParams)
          .then(response => {
            //console.log('responseresponse',response)
            // 关掉loading
            if (objLoading) objLoading.clear();
            // 处理数据逻辑
            // 1. 没有返回data的情况，可能为跨域、超时、断网、连接不上服务器
            const responseData = response.data;
            // // console.log(response,'-------------------------------------------------');
            // if (!responseData) {
            //   // console.log(!responseData,'!responseData!responseData!responseData!responseData!responseData!responseData');
            //   showErrMsg(444, custom.showError);
            //   return reject('网络请求超时！');
            // }
            // // 2. 有size的情况，返回的是文件流，处理成文件格式
            // if (typeof responseData.size === 'number') {
            //   const returnData = { fileName: '', fileData: responseData };
            //   // 从返回头里的content-disposition字段解析出文件名
            //   const contentDisposition = response.headers['content-disposition'] || '';
            //   if (!contentDisposition || !contentDisposition.includes('filename')) return returnData;
            //   const arrFile = contentDisposition.split(';').filter(val => {
            //     return val.includes('filename');
            //   });
            //   if (arrFile.length === 0) return returnData;
            //   returnData.fileName = decodeURIComponent(arrFile[0].replace(/filename=/, ''));
            //   return resolve(returnData);
            // }
            // // 接下来是statusCode===200请求成功的情况。根据code来判断
            // // 3. 当code!==100时，请求有问题
            // if (responseData.code !== 100) {
            //   showErrMsg(204, custom.showError, responseData.message);
            //   return reject(responseData);
            // }
            // 4. 剩下就是接口真正成功并返回最后数据了
            // 处理token，登录接口会在头部返回
            // console.log('custom1111111111111',custom)
            //if (custom.setToken) funSetToken(response);
            resolve(responseData);
            //resolve(response.data);
          })
          .catch(error => {
            // console.log(error,'errorerrorerrorerrorerrorerrorerrorerrorerrorerrorerrorerrorerrorerror');
            // 关掉loading
            if (objLoading) objLoading.clear();
            // 出现服务器类型错误
            const errorCode = !!error.response ? (!!error.response.status ? error.response.status : 444) : 444;
            // console.log('errorCode----------------------',errorCode)
            showErrMsg(errorCode, custom.showError);
            // 再把错误抛出去
            reject(error);
          });
      });
    };
  }

  get(url, params, custom, headers) {
    return this.request('GET', url, params, custom, headers);
  }

  post(url, params, custom, headers) {
    return this.request('POST', url, params, custom, headers);
  }

  put(url, params, custom, headers) {
    return this.request('PUT', url, params, custom, headers);
  }

  delete(url, params, custom, headers) {
    return this.request('DELETE', url, params, custom, headers);
  }

  download(url, params, custom, headers) {
    return this.request('post', url, params, custom, {
      responseType: 'blob',
      ...headers
    });
  }
}

export default new AxiosRequest();
